package study.ssm.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import study.ssm.entity.Cart;
import study.ssm.entity.User;
import study.ssm.service.CartService;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequiredArgsConstructor
@RequestMapping("/cart")
public class CartController {

    private final CartService cartService;

    @GetMapping("/create")
    public String create(Integer productId, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        Cart cart = new Cart();
        cart.setProductId(productId);
        cart.setUserId(loginUser.getId());

        List<Cart> list = cartService.list(cart);
        if (list.isEmpty()) {
            cartService.create(cart);
        }
        return "redirect:/cart/list";
    }

    @GetMapping("/update")
    public String update(Integer id, Model model) {
        Cart cart = cartService.getById(id);
        model.addAttribute("cart", cart);
        return "/cart/update";
    }


    @GetMapping("/remove")
    public String remove(Integer id) {
        cartService.removeById(id);
        return "redirect:/cart/list";
    }

    @PostMapping("/update")
    public String update(Cart cart) {
        cartService.update(cart);
        return "redirect:/cart/list";
    }

    @RequestMapping("/list")
    public String list(Cart cart, Model model, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        Cart param = new Cart();
        param.setUserId(loginUser.getId());
        List<Cart> list = cartService.list(param);
        model.addAttribute("list", list);
        return "/cart/index";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Cart cart = cartService.getById(id);
        model.addAttribute("cart", cart);
        return "/cart/detail";
    }
}
